/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package station;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;

/**
 *
 * @author safe
 */
public class Taktgeber extends Thread {

    private final String interfaceName;
    private final String ip;
    private final int port;
    private final MulticastSocket multicastSocket;

    public Taktgeber(String interfaceName, String ip, int port) {
        this.interfaceName = interfaceName;
        this.ip = ip;
        this.port = port;
        this.multicastSocket = initializeMulticast();
    }

    private void prepareNextFrame() {
        DataSlotBelegung.setAllToFalse();
    }

    private MulticastSocket initializeMulticast() {
        try {
            InetSocketAddress group = new InetSocketAddress(InetAddress.getByName(ip), port);
            MulticastSocket multicastsocket = new MulticastSocket(port);
            NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName);
            multicastsocket.joinGroup(group, networkInterface);

            return multicastsocket;
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            return null;
        }
    }

    @Override
    public void run() {
        long nextFrame = System.currentTimeMillis() + DataAbweichungsZeit.getAbWeichungsZeit() + 1000;
        nextFrame = nextFrame - (nextFrame % 1000);
        while (!isInterrupted()) {
            long abweichungszeit = DataAbweichungsZeit.getAbWeichungsZeit();
            long now = System.currentTimeMillis() + abweichungszeit;

            if (now >= nextFrame) {
                nextFrame = System.currentTimeMillis() + abweichungszeit + 1000;
                nextFrame = nextFrame - (nextFrame % 1000);
                if (DataEmpfangeneNachrichten.getSendingCollision()) {
                    DataSlotBelegung.calculateNextFreeSlot();
                    DataEmpfangeneNachrichten.setSendingCollision(false);
                }
                this.prepareNextFrame();

                Sender sender = new Sender(multicastSocket);
                sender.start();
                try {
                    sleep(900);
                } catch (InterruptedException ex) {
                }
            }
        }
    }
}
